package com.wzq.solution;

import com.wzq.solution.node.ListNode;

class Solution25 {
    
     public static ListNode reverseKGroup(ListNode head, int k) {

         ListNode rst=null;

         ListNode newL = null;
         ListNode rstTail = null;
         ListNode tmpRstTail = null;
        int tk = k;
        while(head != null && tk>0){

            if(tmpRstTail == null){
                tmpRstTail = head;
            }
            ListNode p = head;
            head = head.next;
            p.next = newL;
            newL = p;
            tk--;
            if(tk == 0){
                if(rst == null){
                    rst = newL;
                }else{
                    rstTail.next = newL;

                }
                rstTail = tmpRstTail;
                tmpRstTail = null;
                newL = null;
                tk = k;
            }



        }


        if(tk != 0){
            head = newL;
            newL = null;
            while (head != null){
                ListNode p = head;
                head = head.next;
                p.next = newL;
                newL = p;
            }
            rstTail.next = newL;
        }
        return rst;
    }

    public static ListNode reverseKGroup2(ListNode head, int k) {

        ListNode rst=null;

        ListNode newL = null;
        ListNode rstTail = null;
        ListNode tmpRstTail = null;
        int tk = k;
        while(head != null && tk>0){

            if(tmpRstTail == null){
                tmpRstTail = head;
            }
            ListNode p = head;
            head = head.next;
            p.next = newL;
            newL = p;
            tk--;
            if(tk == 0){
                if(rst == null){
                    rst = newL;
                }else{
                    rstTail.next = newL;

                }
                rstTail = tmpRstTail;
                tmpRstTail = null;
                newL = null;
                tk = k;
            }
        }


        if(tk != 0){
            head = newL;
            newL = null;
            while (head != null){
                ListNode p = head;
                head = head.next;
                p.next = newL;
                newL = p;
            }
            rstTail.next = newL;
        }
        return rst;
    }




    public static void main(String[] args) {
        int[] headArr = new int[]{1};
        ListNode head = new ListNode(headArr[0]);
        ListNode p =head;
        for (int i=1;i<headArr.length; i++){
            p.next = new ListNode(headArr[i]);
            p = p.next;
        }

        head = reverseKGroup(head,2);
        while (head != null){
            System.out.println(head.val);
            head = head.next;
        }
        //System.out.println(964632435*10+1>Math.pow(2,31)-1);
    }
}